let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let expressSession = require('express-session');
let bodyParser = require('body-parser');
let cors = require('cors');
const WeChat = require('wechat');

let app = express();

global.config = require('./config');
global.printLog = require('./lib/customConsole');
global.dbModel = require('./model');
global.mysqlHelper = require('./lib/mysqlHelper');
global.masterPool = require('./lib/mysqlHelper').mysqlPool;
const weChatTool = require('./lib/weChatTool');
const Schedule = require('./schedule/scheduleOfAddNum');
global.weChatApi = weChatTool.api;
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use('/favicon.ico',function (req,res,next) {res.send();});
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.json({limit:"10000kb"}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
    secret: "dashan",
    cookie: {maxAge: 1 * 60 * 60 * 1000},
    resave: true,
    saveUninitialized: true
}));
// app.get('/', function (req,res,next) {
//     console.log("=path==",req.path);
//     console.log("=query==",req.query);
//     res.send(req.query.echostr);
// });
app.use('/wechat', WeChat("hunlian")
    .text(function (message,req,res,next) {
        console.log("=test=",message);
        res.reply('');
    })
    .event(require('./action/weChatCallBackAction').eventHandle).middlewarify()
);
app.use(bodyParser.text({type:"text/xml",defaultCharset: 'utf-8'}));

app.use(express.static(path.join(__dirname, 'public')));

weChatTool.initWeChat();
weChatTool.getAccessToken();
require('./lib/initSomeUtils').initUtils();
app.get('/', function (req,res,next) {
    console.log("=path==",req.path);
    console.log("=query==",req.query);
    // res.send(req.query.echostr);
    next();
});


require('./routes')(app);
Schedule.updateAddNum();


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  printLog(err);
  res.send({code:1,errorInfo:err.message});
});

module.exports = app;
